package com.example.administrator.managesystem.video;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.example.administrator.managesystem.R;
import com.example.administrator.managesystem.activity.firstpage.wiki.WikiDetailActivity;
import com.example.administrator.managesystem.adapter.GridViewAdapter;
import com.example.administrator.managesystem.adapter.ListViewSlideAdapter;
import com.example.administrator.managesystem.base.BaseActivity;
import com.example.administrator.managesystem.base.MyApplication;
import com.example.administrator.managesystem.bean.CameraListBean;
import com.example.administrator.managesystem.bean.GetCameraBean;
import com.example.administrator.managesystem.bean.LandListBean;
import com.example.administrator.managesystem.bean.TagBean;
import com.example.administrator.managesystem.ui.AddLandView;
import com.example.administrator.managesystem.utils.DisplayUtils;
import com.example.administrator.managesystem.utils.ShareUtil;
import com.example.administrator.managesystem.utils.ToastUtils;
import com.example.administrator.managesystem.view.CameraGridDialog;
import com.example.administrator.managesystem.view.ChooseCameraDialog;
import com.example.administrator.managesystem.view.PickLandDialog;
import com.example.administrator.managesystem.view.SlideListView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.squareup.picasso.Picasso;
import com.videogo.constant.IntentConsts;
import com.videogo.openapi.bean.EZCameraInfo;
import com.videogo.openapi.bean.EZDeviceInfo;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class LandListActivity extends BaseActivity implements AddLandView {
    private SwipeMenuListView swipeMenuListView;
    private SwipeMenuCreator creator;
    private ListViewSlideAdapter listViewSlideAdapter;
    private TextView add_land_tv;
    private PickLandDialog landDialog;
    private ChooseCameraDialog chooseCameraDialog;
    private TextView type_tag;
    private List<String> labels_id=new ArrayList<>();
    private List<String> datas = new ArrayList<>();
    private List<LocalMedia> selectList = new ArrayList<>();
    private TagAdapter<String> adapter;
    private AddLandPresenter addLandPresenter;
    private ArrayList<ImageView> img=new ArrayList<>();
    private int type_index=0;
    private CameraGridDialog cameraGridDialog;
    private String landId;
    private String goods_type;
    private EZDeviceInfo mDeviceInfo = null;
    private EZCameraInfo mCameraInfo = null;
    @Override
    public void initView() {

        showfloatButton(true,false);
        swipeMenuListView=findViewById(R.id.swipe_listView);
        add_land_tv=findViewById(R.id.add_land_tv);
        listViewSlideAdapter=new ListViewSlideAdapter(this);
        addLandPresenter=new AddLandPresenter(this);


    }



    @Override
    public void doBusiness() {
        showProgressDialog();

      addLandPresenter.landListRequest(ShareUtil.getUserId(LandListActivity.this),ShareUtil.getUserToken(LandListActivity.this),LandListActivity.this);

      add_land_tv.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            showDialog();
          }
      });
     listViewSlideAdapter.setOnAddClickListener(new ListViewSlideAdapter.OnAddClickListener() {

         @Override
         public void onAddClick(final String land_id ,int position) {
             Log.e("msg","land_id:"+land_id);
             landId=land_id;
             cameraGridDialog=new CameraGridDialog(LandListActivity.this,LandListActivity.this);
             cameraGridDialog.setCanceledOnTouchOutside(false);
             cameraGridDialog.show();
             addLandPresenter.getCameraRequest(ShareUtil.getUserId(LandListActivity.this),ShareUtil.getUserToken(LandListActivity.this),land_id,LandListActivity.this);

             cameraGridDialog.setOnCancelListener(new View.OnClickListener() {
                 @Override
                 public void onClick(View v) {
                     cameraGridDialog.dismiss();
                 }
             });

             cameraGridDialog.setOnEnterListener(new View.OnClickListener() {
                 @Override
                 public void onClick(View v) {
                     cameraGridDialog.dismiss();
                 }
             });
             cameraGridDialog.setOnAddCameraClickListener(new CameraGridDialog.OnAddCameraClickListener() {
                 @Override
                 public void onAddClick(View view, EditText editText) {
                     showProgressDialog();
                     Log.e("msg","editText.getText().toString():"+editText.getText().toString());
                     addLandPresenter.addCameraRequest(ShareUtil.getUserId(LandListActivity.this),ShareUtil.getUserToken(LandListActivity.this),landId,editText.getText().toString(),LandListActivity.this);
                 }
             });
         }
     });

     listViewSlideAdapter.setOnAddCameraClickListener(new ListViewSlideAdapter.OnCameraListClickListener() {
         @Override
         public void onCameraListClick(String land_id, int position) {
           showProgressDialog();

           addLandPresenter.cameraListRequest(ShareUtil.getUserId(LandListActivity.this),ShareUtil.getUserToken(LandListActivity.this),land_id,LandListActivity.this);
         }
     });

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_land_list;
    }


    /**
     * 创建策划的Menu
     */
    private void creatSwipeMenu() {
        creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                // create "open" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(
                        getApplicationContext());
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(153, 153,
                        153)));
                // set item width
                deleteItem.setWidth(DisplayUtils.dp2px(LandListActivity.this,50));
                // set item title
                deleteItem.setTitle("移除");
                // set item title fontsize
                deleteItem.setTitleSize(14);
                // set item title font color
                deleteItem.setTitleColor(Color.WHITE);
                // add to menu
                menu.addMenuItem(deleteItem);
                // create "delete" item
                SwipeMenuItem editItem = new SwipeMenuItem(
                        getApplicationContext());
                // set item background
                editItem.setBackground(new ColorDrawable(Color.rgb(135,
                        180, 33)));
                // set item width
                editItem.setWidth(DisplayUtils.dp2px(LandListActivity.this,50));
                // set a app_icon
                editItem.setTitle("编辑");
                editItem.setTitleSize(14);
                editItem.setTitleColor(Color.WHITE);
                // add to menu
                menu.addMenuItem(editItem);
            }
        };
    }
    /**
     * 点击SwipMenu触发的事件
     *
     * @param swipeMenuListView
     */
    private void onClickListener(final SwipeMenuListView swipeMenuListView, final List<LandListBean.DataBean> list) {
        swipeMenuListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {

                switch (index) {
                    case 0:
                        deleteDialog(list.get(position).getName(),list.get(position).getId(),position);
                        break;
                    case 1:
                        showEditDialog(list.get(position).getId(),list.get(position).getName(),list.get(position).getGoods_name());
                        break;
                }
                return true;
            }
        });

    }

    /**
     * 显示对话框
     */
    private void showDialog() {
        addLandPresenter.goodsTypeRequest(LandListActivity.this);
        landDialog = new PickLandDialog(LandListActivity.this,false,null);
      landDialog.setOnEnterClickListener(new PickLandDialog.OnEnterClickListener() {
      @Override
      public void onEnterClick(View view, EditText editText,TextView location) {
          //如果对话框处于显示状态
          if (landDialog.isShowing()) {
              if(editText.getText().toString().isEmpty()){
                  ToastUtils.showToast(LandListActivity.this,"请添加土地名称");
                  return;
              }
              if(selectList.isEmpty()){
                  ToastUtils.showToast(LandListActivity.this,"请添加土地照片");
                  return;
              }
              showProgressDialog();
              addLandPresenter.addLandSendRequest(ShareUtil.getUserId(LandListActivity.this),ShareUtil.getUserToken(LandListActivity.this),editText.getText().toString(),labels_id.get(type_index),location.getText().toString(),selectList.get(0).getPath(),LandListActivity.this);
          }
      }
  });

        landDialog.setOnCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                landDialog.dismiss();
            }
        });
    landDialog.setOnShowTypeClickListener(new PickLandDialog.OnShowTypeClickListener() {
       @Override
       public void onShowTypeClick(View view, final RelativeLayout type_rl, TagFlowLayout mFlowLayout, final TextView land_tag) {
           type_rl.setVisibility(View.VISIBLE);
           adapter= new TagAdapter<String>(datas) {
               @Override
               public View getView(FlowLayout parent, int position, String o) {

                   type_tag = (TextView) LayoutInflater.from(LandListActivity.this).inflate(R.layout.item_type, parent,false);
                   type_tag.setText(o);
                   return type_tag;
               }
           };
           //adapter.setSelectedList(0);
           mFlowLayout.setAdapter(adapter);

           mFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener()
           {
               @Override
               public boolean onTagClick(View view, int position, FlowLayout parent)
               {
                   land_tag.setText(datas.get(position));
                   type_index=position;
                   adapter.setSelectedList(position);//默认选中第一个
                   return true;
               }
           });

           mFlowLayout.setOnSelectListener(new TagFlowLayout.OnSelectListener()
           {
               @Override
               public void onSelected(Set<Integer> selectPosSet)
               {

                   type_rl.setVisibility(View.GONE);
               }
           });
       }
   });


   landDialog.setOnShowPicClickListener(new PickLandDialog.OnShowPicClickListener() {
       @Override
       public void onShowPicClick(View view, ImageView imageView) {
           //                    // 进入相册 以下是例子：不需要的api可以不写
                   img.add(imageView);
                    PictureSelector.create(LandListActivity.this)
                            .openCamera(PictureMimeType.ofAll())
                            .imageFormat(PictureMimeType.PNG)
                            .previewImage(true)// 是否可预览图片
                            .selectionMode(PictureConfig.SINGLE)
                            .isCamera(true)
                            .compress(true)
                            .glideOverride(160, 160)
                            .minimumCompressSize(100)// 小于 100kb 的图片不压缩
                            .cropCompressQuality(90)// 裁剪压缩质量 默认100
                            .selectionMedia(selectList)
                            .forResult(PictureConfig.CHOOSE_REQUEST);


       }
   });
     landDialog.setCanceledOnTouchOutside(false);
     landDialog.show();
    }

  public void deleteDialog(String land_name, final String id, final int position){
      AlertDialog.Builder builder = new AlertDialog.Builder(LandListActivity.this);
      builder.setTitle(land_name);
      builder.setMessage("确认删除吗?");
      //点击对话框以外的区域是否让对话框消失
      builder.setCancelable(false);
      //设置正面按钮
      builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
              addLandPresenter.deleteLandRequest(ShareUtil.getUserId(LandListActivity.this),ShareUtil.getUserToken(LandListActivity.this),id,position,LandListActivity.this);
              dialog.dismiss();

          }
      });
      //设置反面按钮
      builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();
          }
      });
      builder.create().show();

  }
    public void showEditDialog(final String land_id,String name,String type){
        goods_type=type;
        addLandPresenter.goodsTypeRequest(LandListActivity.this);
        landDialog = new PickLandDialog(LandListActivity.this,true,name);
        landDialog.setOnEnterClickListener(new PickLandDialog.OnEnterClickListener() {
            @Override
            public void onEnterClick(View view, EditText editText,TextView location) {
                //如果对话框处于显示状态
                if (landDialog.isShowing()) {
                    if(editText.getText().toString().isEmpty()){
                        ToastUtils.showToast(LandListActivity.this,"请添加土地名称!");
                        return;
                    }
                    if(selectList.isEmpty()){
                        ToastUtils.showToast(LandListActivity.this,"请添加土地照片!");
                        return;
                    }
                    showProgressDialog();
                    addLandPresenter.updateLandRequest(ShareUtil.getUserId(LandListActivity.this),ShareUtil.getUserToken(LandListActivity.this),editText.getText().toString(),land_id,labels_id.get(type_index),location.getText().toString(),selectList.get(0).getPath(),LandListActivity.this);
                }
            }
        });

        landDialog.setOnCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                landDialog.dismiss();
            }
        });
        landDialog.setOnShowTypeClickListener(new PickLandDialog.OnShowTypeClickListener() {
            @Override
            public void onShowTypeClick(View view, final RelativeLayout type_rl, TagFlowLayout mFlowLayout, final TextView land_tag) {
                type_rl.setVisibility(View.VISIBLE);
                adapter= new TagAdapter<String>(datas) {
                    @Override
                    public View getView(FlowLayout parent, int position, String o) {

                        type_tag = (TextView) LayoutInflater.from(LandListActivity.this).inflate(R.layout.item_type, parent,false);
                        type_tag.setText(o);
                        return type_tag;
                    }
                };
                Log.e("msg","type_index:"+type_index);
               // adapter.setSelectedList(0);
                mFlowLayout.setAdapter(adapter);

                mFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener()
                {
                    @Override
                    public boolean onTagClick(View view, int position, FlowLayout parent)
                    {
                        land_tag.setText(datas.get(position));
                        type_index=position;
                        adapter.setSelectedList(position);//默认选中第一个
                        return true;
                    }
                });

                mFlowLayout.setOnSelectListener(new TagFlowLayout.OnSelectListener()
                {
                    @Override
                    public void onSelected(Set<Integer> selectPosSet)
                    {
                        type_rl.setVisibility(View.GONE);
                    }
                });
            }
        });


        landDialog.setOnShowPicClickListener(new PickLandDialog.OnShowPicClickListener() {
            @Override
            public void onShowPicClick(View view, ImageView imageView) {
                //                    // 进入相册 以下是例子：不需要的api可以不写
                img.add(imageView);
                PictureSelector.create(LandListActivity.this)
                        .openCamera(PictureMimeType.ofAll())
                        .imageFormat(PictureMimeType.PNG)
                        .previewImage(true)// 是否可预览图片
                        .selectionMode(PictureConfig.SINGLE)
                        .isCamera(true)
                        .compress(true)
                        .glideOverride(160, 160)
                        .minimumCompressSize(100)// 小于 100kb 的图片不压缩
                        .cropCompressQuality(90)// 裁剪压缩质量 默认100
                        .selectionMedia(selectList)
                        .forResult(PictureConfig.CHOOSE_REQUEST);


            }
        });
        landDialog.setCanceledOnTouchOutside(false);
        landDialog.show();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    selectList=PictureSelector.obtainMultipleResult(data);
                    Log.e("msg","path:"+selectList.get(0).getPath());
                    File file = new File(selectList.get(0).getPath());
                    Picasso.with(LandListActivity.this).load(file).into(img.get(0));
                    img.clear();
                    break;
            }
        }
    }


    @Override
    public void showLandTag(List<TagBean.DataBean> list) {
        datas.clear();
        for(int i=0;i<list.size();i++){
//         if(goods_type!=null && list.get(i).getCategory_name().equalsIgnoreCase(goods_type)){
//             adapter.setSelectedList(i);
//         }
            datas.add(list.get(i).getCategory_name());
            labels_id.add(list.get(i).getCategory_id());
        }
    }

    @Override
    public void showMsg() {
        landDialog.dismiss();//关闭对话框
        addLandPresenter.landListRequest(ShareUtil.getUserId(LandListActivity.this),ShareUtil.getUserToken(LandListActivity.this),LandListActivity.this);
        dismissProgressDialog();

    }

    @Override
    public void showLandList(List<LandListBean.DataBean> list) {
        Log.e("msg","list："+list);
        dismissProgressDialog();
        listViewSlideAdapter.addDatas(list);
        swipeMenuListView.setAdapter(listViewSlideAdapter);
        creatSwipeMenu();
        // set creator
        swipeMenuListView.setMenuCreator(creator);
        onClickListener(swipeMenuListView,list);
        selectList.clear();
    }

    @Override
    public void showDeleteMsg(String camera_id) {
        addLandPresenter.deleteCameraRequest(ShareUtil.getUserId(LandListActivity.this),ShareUtil.getUserToken(LandListActivity.this),landId,camera_id,LandListActivity.this);
    }

    @Override
    public void showCameraList(List<GetCameraBean.DataBean> list) {
        Log.e("msg","list:"+list);
        dismissProgressDialog();
        cameraGridDialog.addCameraList(list);


    }

    @Override
    public void showCameraRecycler(List<CameraListBean.DataBean> list) {
        dismissProgressDialog();
        if(list.isEmpty()){
            ToastUtils.showToast(this,"抱歉，目前还没有摄像头，赶快添加吧！");
            return;
        }
        chooseCameraDialog=new ChooseCameraDialog(LandListActivity.this,LandListActivity.this);
        chooseCameraDialog.addCameraList(list);
        chooseCameraDialog.setCanceledOnTouchOutside(false);
        chooseCameraDialog.show();
        chooseCameraDialog.setOnCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseCameraDialog.dismiss();
            }
        });

    }

    @Override
    public void updateGrid() {
        Log.e("msg","landId:"+landId);
        dismissProgressDialog();
        addLandPresenter.getCameraRequest(ShareUtil.getUserId(LandListActivity.this),ShareUtil.getUserToken(LandListActivity.this),landId,LandListActivity.this);
    }

    @Override
    public void showUrl(String url,String device_number) {
        chooseCameraDialog.dismiss();
        showProgressDialog();
        Log.e("msg","device_number:"+device_number);
        addLandPresenter.showHikToken(this,ShareUtil.getUserId(this),ShareUtil.getUserToken(this),device_number);


    }

    @Override
    public void showDelete(int position) {
        listViewSlideAdapter.removeData(position);
        listViewSlideAdapter.notifyDataSetChanged();
    }

    @Override
    public void showErrMsg() {
        dismissProgressDialog();
        showerr();

    }

    @Override
    public void showToken(String token,String device_number) {
        MyApplication.getOpenSDK().setAccessToken(token);
        new GetCamersInfoListTask(this,device_number).execute();
    }

    /**
     * 获取事件消息任务
     */
    public class GetCamersInfoListTask extends AsyncTask<Void, Void,  EZDeviceInfo> {
        private boolean mHeaderOrFooter;
        private int mErrorCode = 0;
        private final static int LOAD_MY_DEVICE = 0;
        private final static int LOAD_SHARE_DEVICE = 1;
        private int mLoadType = LOAD_MY_DEVICE;
        private Context context;
        private String device_serial;

        public GetCamersInfoListTask( Context context,String device_serial) {
            this.context = context;
            this.device_serial=device_serial;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
//        //mListView.setFooterRefreshEnabled(true);
//        if (mHeaderOrFooter) {
//            mListView.setVisibility(View.VISIBLE);
//            mNoCameraTipLy.setVisibility(View.GONE);
//            mGetCameraFailTipLy.setVisibility(View.GONE);
//        }
//        mListView.getRefreshableView().removeFooterView(mNoMoreView);
        }

        @Override
        protected  EZDeviceInfo doInBackground(Void... params) {

            EZDeviceInfo  result = null;

            try {

                result =MyApplication.getOpenSDK().getDeviceInfo(device_serial);
                Log.e("msg","result:"+result);

            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;


        }
        @Override
        protected void onPostExecute(EZDeviceInfo result) {
            super.onPostExecute(result);

            if (result != null) {
                mDeviceInfo=result;
                mCameraInfo=mDeviceInfo.getCameraInfoList().get(0);
                Log.e("msg","异步mCameraInfo.getCameraName():"+mCameraInfo.getCameraName());
                Log.e("msg"," 异步mCameraInfo.getDeviceSerial():"+mCameraInfo.getDeviceSerial());
                Log.e("msg","异步mCameraInfo.getCameraNo():"+mCameraInfo.getCameraNo());
                Log.e("msg","异步mDeviceInfo.isSupportTalk():"+mDeviceInfo.isSupportTalk());
                Log.e("msg","异步mDeviceInfo.isSupportZoom():"+mDeviceInfo.isSupportZoom());
                Log.e("msg","异步mDeviceInfo.getStatus():"+mDeviceInfo.getStatus());
                Log.e("msg","异步mDeviceInfo.isSupportPTZ():"+mDeviceInfo.isSupportPTZ());
                Log.e("msg","异步mDeviceInfo.toString():"+mDeviceInfo.toString());
                Log.e("msg","异步mCameraInfo.toString():"+mCameraInfo.toString());
                dismissProgressDialog();
                Intent intent=new Intent(LandListActivity.this,RealPlayActivity.class);
                intent.putExtra(IntentConsts.EXTRA_CAMERA_INFO, mCameraInfo);
                intent.putExtra(IntentConsts.EXTRA_DEVICE_INFO, mDeviceInfo);
                startActivity(intent);
            }
        }
    }
}